package com.hunliji.monitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hunliji.common.exception.WarnException;
import com.hunliji.monitor.dao.mapper.mt.DbInfoMapper;
import com.hunliji.monitor.dao.model.dataobject.DbInfoDO;
import com.hunliji.monitor.service.api.DbInfoService;
import com.hunliji.monitor.service.api.model.bo.DbInfoBO;
import com.hunliji.monitor.service.api.model.param.QueryDbInfoParam;
import com.hunliji.monitor.share.component.ComponentLocator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 数据库信息
 * @author wuchen
 */
@Service
public class DbInfoServiceImpl implements DbInfoService {
    @Resource
    private DbInfoMapper dbInfoMapper;
    @Override
    public void add(DbInfoBO dbInfoBO) {
        DbInfoDO dbInfoDO = ComponentLocator.getConverter().convert(dbInfoBO,DbInfoDO.class);
        dbInfoMapper.insert(dbInfoDO);
    }

    @Override
    public void update(DbInfoBO dbInfoBO) {
        DbInfoDO dbInfoDO = dbInfoMapper.selectById(dbInfoBO.getId());
        if(Objects.isNull(dbInfoDO)){
            throw new WarnException("无法查询到数据库信息");
        }
        dbInfoDO.setName(dbInfoBO.getName());
        dbInfoDO.setRemark(dbInfoBO.getRemark());

        dbInfoMapper.updateById(dbInfoDO);
    }

    @Override
    public DbInfoBO queryById(Long id) {
        DbInfoDO dbInfoDO = dbInfoMapper.selectById(id);
        if(Objects.isNull(dbInfoDO)){
            return null;
        }
        return ComponentLocator.getConverter().convert(dbInfoDO,DbInfoBO.class);
    }

    @Override
    public List<DbInfoBO> query(QueryDbInfoParam queryDbInfoParam) {
        LambdaQueryWrapper<DbInfoDO> queryWrapper = new LambdaQueryWrapper<DbInfoDO>();
        queryWrapper.eq(DbInfoDO::getDeleted,Boolean.FALSE);
        if(StringUtils.isNotBlank(queryDbInfoParam.getName())){
            queryWrapper.eq(DbInfoDO::getName,queryDbInfoParam.getName());
        }
        if(StringUtils.isNotBlank(queryDbInfoParam.getRemark())){
            queryWrapper.like(DbInfoDO::getRemark,queryDbInfoParam.getRemark());
        }
        List<DbInfoDO> dbInfoDOList = dbInfoMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(dbInfoDOList)){
            return new ArrayList<>();
        }
        return ComponentLocator.getConverter().convertList(dbInfoDOList,DbInfoBO.class);
    }
}
